package com.xm.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xm.domain.dto.EmployeeDto;
import com.xm.domain.dto.EmployeeLoginDTO;
import com.xm.domain.po.Employee;
import com.xm.domain.vo.EmployeeLoginVO;
import com.xm.exception.BaseException;
import com.xm.mapper.EmployeeMapper;
import com.xm.properties.JwtProperties;
import com.xm.service.EmployeeService;
import com.xm.utils.BeanUtils;
import com.xm.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {


    private final RedisTemplate redisTemplate;

    private final JwtProperties jwtProperties;

    /**
     * 创建商家
     * @param employeeDto
     */
    @Override
    @Transactional
    public void saveEmployee(EmployeeDto employeeDto) {

        log.info(employeeDto.toString());
        //1 校验邮箱验证码是否正确
         String emailCode = (String) redisTemplate.opsForValue().get(employeeDto.getEmail()+ employeeDto.getEmailCode());
        if (emailCode=="" | emailCode==null){
            throw new BaseException("邮箱验证码输入错误,或者邮箱与申请验证码邮箱不一致");
        }
        //1.1
//        校验当前用户是否已经创建
        Employee one = lambdaQuery().eq(Employee::getEmail, employeeDto.getEmail()).one();
        if (one!=null){
            throw new BaseException("当前邮箱已经创建过");
        }

        //2 校验密码是否正确
        if (!employeeDto.getPassword().equals(employeeDto.getPassword2())){
            throw new BaseException("两次密码不对");
        }

        //3 补充插入数据的信息

        Employee employee= BeanUtils.copyBean(employeeDto, Employee.class);

        employee.setUsername(employeeDto.getEmail());
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));

        boolean save = save(employee);
        if (!save){
            throw new BaseException("商家数据插入失败");

        }

    }


    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {

        //1校验用户名是否存在
        Employee employee = lambdaQuery().eq(Employee::getUsername, employeeLoginDTO.getUsername()).one();
        if (employee==null ){
            throw new BaseException("当前用户不存在");
        }


        //2校验密码是否正确
        //加密前台密码
        String pw = DigestUtils.md5DigestAsHex(employeeLoginDTO.getPassword().getBytes());
        if (!employee.getPassword().equals(pw) ){
            throw new BaseException("密码错误");
        }

        //3封装vo对象
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("emp_id", employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getEmployeeSecretKey(),
                jwtProperties.getEmployeeTtl(),
                claims);
//        builder()，本质上是创建一个EmployeeLoginVO对象，然后调用里面的set方法给属性赋值，这里使用builder()插件可以写的很简洁
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return employeeLoginVO;

    }
}
